<template>
  <div id="box">
    <!-- <el-alert title="请扫码支付" type="info" show-icon></el-alert> -->
    <center>
      <span v-show="refresh">
        <h2 style="color:#20A0FF">二维码已刷新</h2>
      </span>
      <br />
      <span
        class="progress"
        style="color:#666666FF; font-size:14px;"
      >{{allCode-undealedNum+1 }}/{{allCode}}</span>
      <transition
        name="fade"
        v-on:after-leave="afterLeave"
        v-on:before-enter="beforeEnter"
        v-on:before-leave="beforeLeave"
      >
        <div id="qrcode" v-show="show"></div>
      </transition>

      <div class="status" style="margin:10px">
        <b>{{status}}</b>
      </div>
      <div v-show="notice" style="font-size:16px; font-weight:bold">请使用云闪付APP扫码支付</div>
    </center>
  </div>
</template>


<script>
import { getQrUrl } from "../api/api";
import QRCode from "qrcodejs2";
import { queryResult } from "../api/api";
import { queryRemainCode, queryAllCode } from "../api/api";
export default {
  data() {
    return {
      qrcodeObj: null,
      src: "",
      id: this.$route.params.id,
      allCode: 0,
      undealedNum: 0,
      percentage: 0,
      status: "未扫码",
      notice: true,
      refresh: false,
      show: true,
      terminal_trace:{}
    };
  },
  methods: {
    qrcode() {
      new QRCode("qrcode", {
        width: 250,
        height: 250, // 高度
        text: this.src // 二维码内容
        // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        // background: '#f0f'
        // foreground: '#ff0'
      });
    },
    makeQrcode() {
      let terminal_trace = this.getUuid(27,16);
      this.terminal_trace = {"terminal_trace":terminal_trace};
      //console.log(this.terminal_trace);
      getQrUrl(this.terminal_trace).then(data => {
        if (data.data.code == -1) {
          document.getElementById(
            "qrcode"
          ).innerHTML = `<h2>${data.data.msg}</h2/`;
          return;
        }
        this.src = data.data.url;
        this.qrcode();
      });
    },
    queryPay() {
      //console.log(this.terminal_trace);
      queryResult(this.terminal_trace).then(data => {
        let code = data.data.result;
        console.log(code);
        if (code == "1") {
          //支付成功
          this.status = "支付成功";
          document.getElementsByClassName("status")[0].style.color = "red";
          this.notice = false;
          let loadingInstance = this.$loading({
            target: "#qrcode",
            text: "支付成功，刷新中",
            background: 'rgba(255,255,255,255)'
          });
          this.refresh = false;
          setTimeout(() => {
            this.$nextTick(() => {
              // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close();
              this.show = false;
            });
          }, 2000);
        } else if (code == "2") {
          this.status = "支付失败";
          this.notice = false;
          document.getElementsByClassName("status")[0].style.color = "red";
          let loadingInstance = this.$loading({
            target: "#qrcode",
            text: "支付失败，刷新中",
            background: 'rgba(255,255,255,255)'
          });
          setTimeout(() => {
            document.getElementById("qrcode").innerHTML = "";
            this.makeQrcode();
            this.getPercentage();
            this.$nextTick(() => {
              // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close();
            });
          }, 2000);
          this.notice = true;
          document.getElementsByClassName("status").style.color = "black";
          this.refresh = true;
          setTimeout(() => {
            this.refresh = false;
          }, 4000);
        } else {
          this.status = "未扫码";
        }
      });
    },
    getPercentage() {
      queryRemainCode().then(data => {
        this.undealedNum = parseInt(data.data.count);
        //console.log(this.undealedNum);
      });
      queryAllCode().then(data => {
        this.allCode = parseInt(data.data.count);
        this.percentage = ((this.undealedNum * 10) / this.allCode) * 10;
        //console.log(this.allCode);
      });
    },
    beforeLeave() {
      this.refresh = false;
    },
    afterLeave() {
      document.getElementById("qrcode").innerHTML = "";
      this.makeQrcode();
      this.show = !this.show;
      this.status = "未扫码";
      document.getElementsByClassName("status")[0].style.color = "black";
    },
    beforeEnter() {
      this.getPercentage();
      this.notice = true;
      this.refresh = true;
    },
    getUuid(len, radix) {
      var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
        ""
      );
      var uuid = [],
        i;
      radix = radix || chars.length;

      if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        // rfc4122, version 4 form
        var r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }

      return uuid.join("");
    }
  },
  computed: {
    
  },
  mounted() {
    this.getPercentage();
    this.makeQrcode();
    setInterval(() => {
      this.queryPay();
    }, 5000);
  }
};
</script>

<style lang="less" scoped>
#box {
  width: 100%;
  height: 500px;
  display: flex; //flex布局
  justify-content: center; //使子项目水平居中
  align-items: center; //使子项目垂直居中
  #qrcode {
    margin: 10px 0;
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 2s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}

</style>
